package com.reading.core.crawler.process;

import com.reading.common.constant.BookType;
import com.reading.common.entity.view.Book;
import com.reading.core.crawler.constant.ProcessConstant;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * @author guwenqi_1995@163.com
 * @projectName alone-reading
 * @description: TODO
 * @date 2019/8/8 12:31
 */
@Slf4j
public class BiqutxtBookProcess {

    public static Book processBiqutxt(Document html){
        Book book = new Book();

        try {
            //查找图书的基础信息
            Element bookInfo = html.getElementById("maininfo");
            getBookInfo(book, bookInfo);

            //查找图书的封面
            Element bookImgInfo = html.getElementById("fmimg");
            Element image = bookImgInfo.getElementsByTag("img").get(0);
            book.setBookImg(image.attr("src"));

            //查找图书的类型
            Elements conTop = html.getElementsByClass("con_top");
            String content = conTop.get(0).text();
            content = content.substring(content.indexOf(" > ") + 3, content.indexOf("小说 > "));
            book.setBookType(BookType.getTypeCode(content));

            book.setCreateBy("admin");
            book.setUpdateBy("admin");
        } catch (Exception e) {
            log.error("爬取 图书：{} 信息错误。");
            return new Book();
        }

        return book;
    }

    private static void getBookInfo(Book book, Element bookInfo) {
        StringBuffer buffer = new StringBuffer();
        Element info = bookInfo.getElementById("info");

        book.setBookName(info.getElementsByTag("h1").get(0).text());

        String author = info.getElementsByTag("p").get(0).text();
        book.setBookAuthor(author.substring(author.indexOf(ProcessConstant.BIQUTXT_AUTHOR_LABEL)
                + ProcessConstant.BIQUTXT_AUTHOR_LABEL.length()));

        Element intro = bookInfo.getElementById("intro");
        book.setBookDescr(intro.getElementsByTag("p").get(0).text());
    }

    public static Book crawler(String bookCode) throws IOException {
        String url = ProcessConstant.BIQUTXT_DOMAIN_NAME + bookCode;

        Document html = Jsoup.connect(url).get();
        Book book = processBiqutxt(html);

        log.info("book info : {}", book.toString());

        return book;
    }

    public static void main(String[] args) {
        String url = ProcessConstant.BIQUTXT_DOMAIN_NAME + "/0_312";

        try {
            Document html = Jsoup.connect(url).get();
            processBiqutxt(html);
        } catch (IOException e) {
            log.error("爬取 笔趣阁 图书失败", e);
        }
    }

}
